package com.flyme.module.order.provider.unionpay;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.module.order.client.entity.Order;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * HTTP通讯范例: 直接支付
 */
public class ZSHttpRequest {
    /**
     * 生成请求报文
     *
     * @return
     */
    public String getRequestStr(Order order, String dbtbnk) {
        // 构造支付的请求报文
        XmlPacket xmlPkt = new XmlPacket("FBCUPDPD", "银企直连测试用户46");
        Map mpPodInfo = new Properties();
        xmlPkt.putProperty("DCCUPDPDY", mpPodInfo);
        Map mpPayInfo = new Properties();
        //mpPayInfo.put("BBKNBR", "75");//付方分行
        //mpPayInfo.put("ACCNBR", "755915704510504");//账号
//        mpPayInfo.put("RETURL", "http://127.0.0.1:9555/#/success");//前台通知地址
        mpPayInfo.put("RETURL", "http://120.79.205.116:81/base/common/pc/unnpay");//前台通知地址
        mpPayInfo.put("FINURL", "http://120.79.205.116/base/common/unionpay_back");//后台通知地址
        mpPayInfo.put("DBTBNK", dbtbnk);//银行
        mpPayInfo.put("ORDTYP", "1");//订单支付类型付 款 方 银 行 为CMB 时 必输1、直接商务支付2、担保支付
        mpPayInfo.put("ORDCFM", "N");//订单需商户确认标志
        mpPayInfo.put("ORDDAT", DateUtil.today().replaceAll("-", ""));//订单发送日期如：20190222
        mpPayInfo.put("ORDTIM", DateTime.now().toTimeStr().replaceAll(":", ""));//订单发送时间
        mpPayInfo.put("REFORD", order.getOutTradeNo());//订单号
        mpPayInfo.put("TRSAMT", String.valueOf(order.getOrderAmount()));//交易金额
        mpPayInfo.put("ORDAMT", String.valueOf(order.getOrderAmount()));//订单金额
        mpPayInfo.put("CCYNBR", "10");//交易币种
        mpPayInfo.put("RCVACC", "755915704510504");//收方账号
        xmlPkt.putProperty("NTCUPDPDX1", mpPayInfo);
        return xmlPkt.toXmlString();
    }

    /**
     * 验证签名报文
     */
    public String verifySign(String content, String sign) {
        content = content.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
            .replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
        // 构造支付的请求报文
        XmlPacket xmlPkt = new XmlPacket("VerifySignature");
        Map mpPayInfo = new Properties();
        mpPayInfo.put("SRCDAT", content);//内容
        mpPayInfo.put("SIGDTA", sign);//签名
        xmlPkt.putProperty("SDKTRDVSX", mpPayInfo);
        return xmlPkt.toXmlString();
    }

    /**
     * 查询订单
     */
    public String findOrder(String orderNo) {
        // 构造支付的请求报文
        XmlPacket xmlPkt = new XmlPacket("NTCBOQSD", "银企直连测试用户46");
        Map mpPayInfo = new Properties();
        mpPayInfo.put("ACCNBR", "755915704510504");//收款账号
        mpPayInfo.put("PAYNBR", orderNo);//支付流水号
        xmlPkt.putProperty("NTCBOQSDX1", mpPayInfo);
        return xmlPkt.toXmlString();
    }

    /**
     * 资金对账（查询历史通知）
     */
    public String findOldMsg(String startDate, String endDate, String msgType) {
        // 构造支付的请求报文
        XmlPacket xmlPkt = new XmlPacket("GetHisNoticeEX", "银企直连测试用户46");
        Map mpPayInfo = new Properties();
        mpPayInfo.put("BGNDAT", startDate);//开始日期
        mpPayInfo.put("ENDDAT", endDate);//结束日期
        mpPayInfo.put("MSGTYP", msgType);//消息类型
        xmlPkt.putProperty("DCHISMSGX", mpPayInfo);
        return xmlPkt.toXmlString();
    }

    /**
     * 连接前置机，发送请求报文，获得返回报文
     *
     * @param data
     * @return
     * @throws MalformedURLException
     */
    public String sendRequest(String data) {
        String result = "";
        try {
            URL url;
            url = new URL("http://localhost:8080");

            HttpURLConnection conn;
            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os;
            os = conn.getOutputStream();
            os.write(data.toString().getBytes("gbk"));
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn
                .getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                result += line;
            }

            System.out.println(result);
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 处理返回的结果
     *
     * @param result
     */
    public void processResult(String result) {
        if (result != null && result.length() > 0) {
            XmlPacket pktRsp = XmlPacket.valueOf(result);
            if (pktRsp != null) {
                String sRetCod = pktRsp.getRETCOD();
                if (sRetCod.equals("0")) {
                    Map propPayResult = pktRsp.getProperty("NTQPAYRQZ", 0);
                    String sREQSTS = (String) propPayResult.get("REQSTS");
                    String sRTNFLG = (String) propPayResult.get("RTNFLG");
                    if (sREQSTS.equals("FIN") && sRTNFLG.equals("F")) {
                        System.out.println("支付失败："
                            + propPayResult.get("ERRTXT"));
                    } else {
                        System.out.println("支付已被银行受理（支付状态：" + sREQSTS + "）");
                    }
                } else if (sRetCod.equals("-9")) {
                    System.out.println("支付未知异常，请查询支付结果确认支付状态，错误信息："
                        + pktRsp.getERRMSG());
                } else {
                    System.out.println("支付失败：" + pktRsp.getERRMSG());
                }
            } else {
                System.out.println("响应报文解析失败");
            }
        }
    }

    public static String openResult(String result){
        XmlPacket pktRsp = XmlPacket.valueOf(result);
        Map<String, Object> urlResult = (Map<String, Object>) pktRsp.data;
        List<Map<String, Object>> u = (List<Map<String, Object>>) urlResult.get("DCCUPDPDY");
        if(ObjectUtils.isEmpty(u)){
            return "";
        }
        String url = String.valueOf(u.get(0).get("GENURL"));
        return url;
    }

    public static void main(String[] args) {

    }

}